package com.jus.player.api;

import android.app.Activity;

import com.alibaba.fastjson2.JSONObject;
import com.jus.player.R;
import com.jus.player.util.CommonUtils;

import java.util.HashMap;
import java.util.Map;

public class GoogleApi {

    private final String ACCESS_TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
    private final String FIND_ORDER_STATE_URL = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/com.jus.tv1/purchases/products/{productId}/tokens/{token}";
    private final String CLIENT_SECRET = "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";
    private final String REFRESH_TOKEN = "";
    private Activity activity;
    private String accessToken;

    public GoogleApi(Activity activity) {
        this.activity = activity;
    }

    /**
     * 1. 使用refreshToken获取accessToken
     * 2. 查询订单状态
     */
    public void getAccessToken(String productId, String token, OkHttpHelper.HttpCallback callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "refresh_token");
        map.put("refresh_token", REFRESH_TOKEN);
        map.put("client_id", activity.getString(R.string.web_oauth_client_id));
        map.put("client_secret", CLIENT_SECRET);
        OkHttpHelper.getInstance(activity).postJsonAsync(ACCESS_TOKEN_URL, map,
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String res) {
                        JSONObject jo = JSONObject.parseObject(res);
                        accessToken = jo.getString("access_token");
                        //查询订单状态
                        Map<String, String> map = new HashMap<>();
                        map.put("access_token", accessToken);
                        String url = FIND_ORDER_STATE_URL.replace("{productId}", productId)
                                .replace("{token}", token);

                        OkHttpHelper.getInstance(activity).getAsync(url, map,
                                new OkHttpHelper.HttpCallback() {
                            @Override
                            public void onSuccess(String res) {

                            }

                            @Override
                            public void onFailure(OkHttpHelper.HttpException e) {

                            }
                        });
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.showToastAsync(activity, e.getMessage());
                    }
                });
    }

}
